package com.twm.tamauth.engine.interceptor

import okhttp3.Headers
import okhttp3.Interceptor
import okhttp3.Response

/**
 * 请求头公参拦截器
 * @property headers 请求头
 */
class MyAuthHeaderInterceptor(
    private val headers: () -> HashMap<String, String?>
) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val method = chain.request().method
        if (method == "POST") {
            return processPost(chain)
        }
        return chain.proceed(chain.request().newBuilder().headers(header(chain)).build())
    }

    private fun processPost(chain: Interceptor.Chain): Response {
        val body = chain.request().body ?: return chain.proceed(
            chain.request().newBuilder().headers(header(chain)).build()
        )
        return chain.proceed(
            chain.request().newBuilder().headers(header(chain)).post(body).build()
        )
    }

    // 添加公参到Header
    private fun header(chain: Interceptor.Chain): Headers {
        val common = headers.invoke()
        val path = chain.request().url.toUrl().path
        val b = chain.request().headers.newBuilder()
        common.forEach {
            it.value?.let { v ->
                b.add(it.key, v)
            }
        }
        return b.build()
    }
}